﻿using System;
using System.Reactive.Linq;
using System.Timers;

namespace Event.ReactiveProgrammingConsole
{
    public class TimerObservable
    {
        public void CreateTimer()
        {
            var ob = Observable.Create<string>(
                observer =>
                {
                    var timer = new Timer
                    {
                        Enabled = true,
                        Interval = 100
                    };
                    timer.Elapsed += OnTimerElapsed;
                    timer.Start();
                    return () =>
                    {
                        timer.Elapsed -= OnTimerElapsed;
                        timer.Dispose();
                    };
                });
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine(e.SignalTime);
        }

        public void UsingTimer()
        {
            var timer = new Timer() { Interval = 1000 };
            timer.Start();

            var eventStream = Observable.FromEventPattern<ElapsedEventArgs>(timer, "Elapsed");
            var nowTime = DateTime.Now;

            var filteredEvents = from e in eventStream
                                 let time = e.EventArgs.SignalTime
                                 where
                                     time > nowTime.AddSeconds(5) &&
                                     time < nowTime.AddSeconds(20)
                                 select e;

            filteredEvents.Subscribe(t => Console.WriteLine(DateTime.Now));
            Console.WriteLine("Let us wait..");

            Console.ReadKey();
        }

    }
}